#资源管理 add by Luxh

sys_resource = require('../models/sys_resource')
SysResource = sys_resource.SysResoure
sys_user = require('../models/sys_user')
SysUser = sys_user.SysUser
SysRole = require('../models/sys_role').SysRole
util = require("util")
resErr = require('./util').resErr
common_util = require('../services/common_util')
dataPage = require('../services/dataPage').queryPage


#资源列表
exports.res_list = (req,res) ->
  parent_id = req.param("parent_id")
  console.log(parent_id)
  if !parent_id
    parent_id = '0'
  params = {"res_parent":parent_id}
  sorts = {_id:-1}
  dataPage SysResource,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"),(err,results) ->
    if err
      resErr(res,err)
    else
      res.json(results)


exports.res_tree = (req,res) ->
  SysResource.find({}).sort({order:1}).exec (err,resources) ->
    if err
      resErr(res,err)
    else
      tree_data = []
      tree_data.push {id:'0', pId:'', name:"资源根节点", open:true,url:"list.html?parent_id=0",target:"rightFrame"}
      for r in resources
        tree_data.push {id:r._id,pId:r.res_parent,name:r.res_name,url:'list.html?parent_id='+r._id,target:"rightFrame"}
      res.json(tree_data)


#添加资源
exports.res_add = (req,res) ->
  order = req.param("order")
  console.log "order===================="
  console.log order
  res_code = common_util.trim(req.param("res_code"))
  res_name = common_util.trim(req.param("res_name"))
  if res_code == null or res_code == ""
    res.json({'flag':'error','msg':'资源编码不能为空！'})
  else if res_name == null or res_name == ""
    res.json({'flag':'error','msg':'资源名称不能为空！'})
  else
    sys_resource.isResourceExist res_code,(err,count) ->
      if(err)
        res.json({'flag':'error','msg':err})
      else
        if count>0
          res.json({'flag':'error','msg':'资源编码已存在！'})
        else
          sys_resource.save req,(err) ->
            if(err)
              console.error(err)
              res.json({'flag':'error','msg':'保存出错！'})
            else
              res.json({'flag':'success','msg':'保存成功！'})


#查看资源
exports.res_detail = (req,res) ->
  _id = req.param("_id")
  if !_id
    res.json({'success':false,'err_msg':'编码不得为空！'})
  else
    SysResource.findById _id,(err,result) ->
      if err
        resErr(res,err)
      else
        res.json(result)


#修改资源
exports.res_edit = (req,res) ->
  _id = req.param("_id")
  if !_id
    res.json({'flag':'error','msg':'编码不得为空！'})
  else
    res_code = common_util.trim(req.param("res_code"))
    res_name = common_util.trim(req.param("res_name"))
    if res_code == null or res_code == ""
      res.json({'flag':'error','msg':'资源编码不能为空！'})
    else if res_name == null or res_name == ""
      res.json({'flag':'error','msg':'资源名称不能为空！'})
    else
      SysResource.count {"_id":{"$ne":_id},"res_code":res_code},(err,count) ->
        if err
          resErr(res,err)
        else
          if count>0
            res.json({'flag':'error','msg':'资源编码已存在！'})
          else
            SysResource.findById _id,(err,resource) ->
              if err
                resErr(res,err)
              else
                resource.res_code = req.param("res_code")
                resource.res_name = req.param("res_name")
                resource.url = req.param("url")
                resource.http_method = req.param("http_method")
                resource.status = req.param("status")
                resource.type = req.param("type")
                resource.order = req.param("order")
                resource.save (err) ->
                  if err
                    console.error(err)
                    res.json('flag':'error','msg':err)
                  else
                    res.json('flag':'success')


#删除资源
exports.res_del = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    _id = req.param('_id')
    SysResource.count {"res_parent":_id},(err,count) ->
      if err
        resErr(res,err)
      else
        if count > 0
          res.json('flag':'error','msg':"该资源下有子资源，不能删除！")
        else
          SysResource.findByIdAndRemove _id,(err)->
            if err
              resErr res,err
            else
              res.json('flag':'success')


#获取已授权的资源
exports.res_authed_list = (req,res) ->
  if req.session?.admin_user
      user = req.session?.admin_user
      if user?.username
        username = user.username
        SysUser.findOne {"username":username},(err,user) ->
          if err
            resErr(res,err)
          else
            if user and user.roles
              SysRole.find {"_id":{"$in":user.roles}},{"role_code":1},(err,roles) ->
                if err
                  resErr(res,err)
                else
                  is_admin = false
                  auth_roles = []
                  for role in roles
                    auth_roles.push role.role_code
                    if role.role_code == 'admin' or role.role_code == 'ADMIN'
                      is_admin = true
                  req.session.auth_roles = auth_roles
                  if is_admin
                    node = '0'
                    menu_array = []
                    SysResource.find({"res_parent":node}).sort({order:1}).exec (err,docs) ->
                      if err
                        resErr(res,err)
                      else
                        SysResource.find {"res_parent":{"$ne":'0'},"type":"menu"},(err,children) ->
                          if err
                            resErr(res,err)
                          else
                            for doc in docs
                              child_array = []
                              for child in children
                                if child.res_parent.toString() == doc._id.toString()
                                  child_array.push {"text":child.res_name,"leaf":true,"hrefTarget":child.url,"id":child._id}
                              menu_array.push {"text":doc.res_name,"leaf":false,"id":doc._id,"children":child_array}
                            res.json({'data':menu_array})
                  else
                    sys_user.findUserRoleByUsername username,(err,urls) ->
                      if err
                        resErr(res,err)
                      else
                        if !urls
                          resErr(res,"当前登录用户还未被授予权限",403)
                        else
                          req.session.auth_urls = urls
                          node = '0'
                          menu_array = []
                          SysResource.find({"res_parent":node}).sort({order:1}).exec (err,docs) ->
                            if err
                              resErr(res,err)
                            else
                              SysResource.find {"res_parent":{"$ne":'0'},"type":"menu"},(err,children) ->
                                if err
                                  resErr(res,err)
                                else
                                  for doc in docs
                                    child_array = []
                                    for url in urls
                                      if url.res_id.toString() == doc._id.toString()
                                        for child in children
                                          if child.res_parent.toString() == doc._id.toString()
                                            for url2 in urls
                                              if url2.res_id.toString() == child._id.toString()
                                                child_array.push {"text":child.res_name,"leaf":true,"hrefTarget":child.url,"id":child._id}
                                                break
                                        menu_array.push {"text":doc.res_name,"leaf":false,"id":doc._id,"children":child_array}
                                        break
                                  res.json({'data':menu_array})
            else
              resErr(res,"当前登录用户未初始化权限",403)
      else
        resErr(res,"无法获取登录用户名")
    else
      resErr(res,"无法获取登录用户或登录信息已过期")




